﻿using NewsPortal.Web.Infrastructure.BaseControllers;
using NewsPortal.Web.Infrastructure.Filters;
using NewsPortal.Web.Infrastructure.Modularity;
using NewsPortal.Web.Infrastructure.Modularity.ModuleControllerFactory;
using Resources;
using System;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Web.Mvc;

namespace NewsPortal.Web.Controllers
{
    public class ModuleRouterController : BaseController
    {
        private IControllerActionFactory _actionFactory;
        private Controller _currentModuleController;
        private MethodInfo _currentModuleAction;
     
        public ModuleRouterController(IControllerActionFactory actionFactory)
        {
            this._actionFactory = actionFactory;
        }

        [Localized]
        public ActionResult Index()
        {
            return this._currentModuleAction.Invoke(this._currentModuleController, null) as ActionResult;
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = RouteData.Values["ActionName"].ToString();
            string moduleName = RouteData.Values["ModuleName"].ToString();

            this._currentModuleController = GlobalModuleControllerCollection.Get(moduleName);
            if (this._currentModuleController == null)
            {
                filterContext.Result =  
                    new HttpStatusCodeResult(HttpStatusCode.NotFound, 
                        String.Format("The Module {0} couldnt be found", actionName));

                return;
            }

            this._currentModuleAction = 
                _actionFactory.CreateAction(this._currentModuleController, actionName);

            base.OnActionExecuting(filterContext);
        }
    }
}